package com.mcxx.modules.minimumliving.service.impl;

import com.alibaba.fastjson.JSON;
import com.mcxx.common.exception.BizException;
import com.mcxx.modules.minimumliving.service.BankService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.family.dto.BankExcelDTO;
import com.mcxx.modules.miniSalvation.family.dto.BankExcelMinDTO;
import com.mcxx.modules.miniSalvation.family.dto.ShowDTO;
import com.mcxx.modules.miniSalvation.family.dto.SpeedProgressDTO;
import com.mcxx.modules.miniSalvation.family.entity.BankEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMainEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.param.BankParam;
import com.mcxx.modules.miniSalvation.family.service.read.BankReadService;
import com.mcxx.modules.miniSalvation.family.service.write.*;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCertReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.system.entity.TaskExportEntity;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMainEntity;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMemberEntity;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMainHistoryWriteService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMainWriteService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMemberHistoryWriteService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMemberWriteService;
import com.mcxx.modules.temporary.order.entity.TmpOrderEntity;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.modules.temporary.order.service.write.TmpOrderWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.*;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mcxx.redis.client.RedisClusterUtils;

import java.util.List;


@Service
@TaTransactional
public class BankServiceImpl extends BaseService implements BankService {
    private static final Logger logger = LoggerFactory.getLogger(CompletedServiceImpl.class);
    @Autowired
    private BankReadService bankReadService;
    @Autowired
    private BankWriteService bankWriteService;
    @Autowired
    private RedisClusterUtils redisClusterUtils;
    @Autowired
    private FileService fileService;
    @Autowired
    private TaskExportWriteService taskExportWriteService;
    @Autowired
    private ExportExcelService exportExcelService;
    @Autowired
    private OrderCertReadService orderCertReadService;

    @Autowired
    private OrderReadService orderReadService;

    @Autowired
    private TmpOrderReadService tmpOrderReadService;
    @Autowired
    private TmpOrderWriteService tmpOrderWriteService;

    @Autowired
    private TmpFamilyMemberWriteService tmpFamilyMemberWriteService;

    @Autowired
    private TmpFamilyMemberHistoryWriteService tmpFamilyMemberHistoryWriteService;

    @Autowired
    private TmpFamilyMainWriteService tmpFamilyMainWriteService;
    @Autowired
    private TmpFamilyMainHistoryWriteService tmpFamilyMainHistoryWriteService;

    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private FamilyMemberWriteService familyMemberWriteService;

    @Autowired
    private FamilyMemberHistoryWriteService familyMemberHistoryWriteService;

    @Autowired
    private FamilyMainWriteService familyMainWriteService;

    @Autowired
    private FamilyMainHistoryWriteService familyMainHistoryWriteService;

    @Override
    public Page getBankPage(UserAccountVo userAccountVo, BankParam param,  PageParam pageParam) {

        QueryParamUtil.setBaseParamValue(param, userAccountVo);

        param.setRescueyears(CommonUtil.invalidArgs(param.getRescueyears()) ? DateUtil.getMonthString() : param.getRescueyears());

        return bankReadService.getBankPage(param, pageParam);
    }

    @Override
    public Page getBankPageMin(UserAccountVo userAccountVo, BankParam param,  PageParam pageParam) {

        QueryParamUtil.setBaseParamValue(param, userAccountVo);

        param.setRescueyears(CommonUtil.invalidArgs(param.getRescueyears()) ? DateUtil.getMonthString() : param.getRescueyears());

        return bankReadService.getBankPageMin(param, pageParam);
    }


    @Override
    public void updateBankInfo(BankEntity dto,UserAccountVo accountVo) {

        this.verifyOrderCaregiver(dto);

        if("1".equals(dto.getIsUpdateName())){
            String orderId = dto.getOrderId();
            String menberId = dto.getMemberId();
            String familyId = dto.getFamilyId();
            String masterName = dto.getMasterName();
            String apName = dto.getApName();

            if(Constant.BusinessCode.LINSHI.equals(dto.getBusinessType())){

                int count = tmpOrderReadService.getByIdCount(orderId);
                TmpOrderEntity orderEntity = new TmpOrderEntity();
                orderEntity.setId(orderId);
                if(count > 0){
                    orderEntity.setName(masterName);
                    orderEntity.setApplyName(masterName);


                    TmpFamilyMainEntity tmpFamilyMainEntity = new TmpFamilyMainEntity();
                    tmpFamilyMainEntity.setName(apName);
                    tmpFamilyMainEntity.setId(familyId);
                    tmpFamilyMainWriteService.updateFamily(tmpFamilyMainEntity);

                    tmpFamilyMainHistoryWriteService.updateMemberName(apName,orderId,familyId);
                }else{
                    orderEntity.setApplyName(apName);
                }

                tmpOrderWriteService.updateOrder(orderEntity);

                TmpFamilyMemberEntity tmpFamilyMemberEntity = new TmpFamilyMemberEntity();
                tmpFamilyMemberEntity.setId(menberId);
                tmpFamilyMemberEntity.setName(apName);
                tmpFamilyMemberWriteService.updateFamilyMember(tmpFamilyMemberEntity);

                tmpFamilyMemberHistoryWriteService.updateMemberName(apName,orderId,menberId);

            }else if(Constant.BusinessCode.DIBAO.equals(dto.getBusinessType())){

                if(Constant.DomesticRelation.ONESELF.equals(dto.getFamilyRelation())){
                    this.updateMemberName(orderId,menberId,familyId,apName);
                }else{

                    FamilyMemberEntity familyMemberEntity = new FamilyMemberEntity();
                    familyMemberEntity.setId(menberId);
                    familyMemberEntity.setName(apName);
                    familyMemberWriteService.updateFamilyMember(familyMemberEntity);

                    familyMemberHistoryWriteService.updateMemberName(apName,orderId,menberId);
                }
            }else{
                this.updateMemberName(orderId,menberId,familyId,masterName);
            }
        } else {

             if(Constant.BusinessCode.LINSHI.equals(dto.getBusinessType())){

                 List<BankEntity> rst = bankReadService.getBankByApplyIdCardAndBizType(dto.getApIdcard(),Constant.BusinessCode.LINSHI);
                 if (rst.size() == 0) {

                     dto.setId(Constant.getUUID());
                     dto.setAreaCode(accountVo.getAreaCode());
                     bankWriteService.insertIgnoreNull(dto);
                 } else {
                     bankWriteService.updateBankInfo(dto, accountVo);
                 }
            } else {
                bankWriteService.updateBankInfo(dto,accountVo);
            }
        }
    }

    public void updateMemberName(String orderId,String menberId,String familyId,String masterName){

        int count = orderReadService.getByIdCount(orderId);
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderId);
        if(count > 0){
            orderEntity.setName(masterName);
            orderEntity.setApplyName(masterName);
        }else{
            orderEntity.setName(masterName);
        }
        orderWriteService.updateIgnoreNull(orderEntity);

        FamilyMemberEntity familyMemberEntity = new FamilyMemberEntity();
        familyMemberEntity.setId(menberId);
        familyMemberEntity.setName(masterName);
        familyMemberWriteService.updateFamilyMember(familyMemberEntity);

        familyMemberHistoryWriteService.updateMemberName(masterName,orderId,menberId);

        FamilyMainEntity familyMainEntity = new FamilyMainEntity();
        familyMainEntity.setName(masterName);
        familyMainEntity.setId(familyId);
        familyMainWriteService.updateFamily(familyMainEntity);

        familyMainHistoryWriteService.updateMemberName(masterName,orderId,familyId);
    }


    public void verifyOrderCaregiver(BankEntity dto){

        int rsts;
        if(Constant.BusinessCode.LINSHI.equals(dto.getBusinessType())){
            rsts = orderCertReadService.cntCertNumTmp(dto.getMemberId(),dto.getOrderId(),"102","2");
        }else{
            rsts = orderCertReadService.cntCertNum(dto.getMemberId(),dto.getOrderId(),"102","2");
        }

        if(rsts <= 0){
            throw new BizException("-1", "当前信息没有上传【身份证照片】，请上传！");
        }

        int rst;
        if(Constant.BusinessCode.LINSHI.equals(dto.getBusinessType())){
            rst = orderCertReadService.cntBankTempCertNum(dto.getMemberId(),dto.getOrderId());
        }else{
            rst = orderCertReadService.cntBankCertNum(dto.getMemberId(),dto.getOrderId());
        }

        if(rst <= 0){
            throw new BizException("-1", "当前银行卡信息没有上传【银行卡照片】，请上传！");
        }
    }

    @Override
    public BaseResult<List<SpeedProgressDTO>> getSpeedProgress(String businessCode,String userId) {
        BaseResult<List<SpeedProgressDTO>> result = new BaseResult<>();
        String redisKey = "speedprogress_"+businessCode+"_"+userId;
        try {
            if (redisClusterUtils.get(redisKey) != null) {
                Object val = redisClusterUtils.get(redisKey);
                if(null != val) {
                    ShowDTO s = JSON.parseObject(val.toString(), ShowDTO.class);
                    result.setData(s.getSpList());
                }
            }
            return result;
        } catch (Exception e) {
            logger.error("根据ID获取行政区域详情异常" + e.getMessage());
            e.printStackTrace();
            result.setCode(FailureCode.ERR_9999.getCode());
            result.setMsg(FailureCode.ERR_9999.getMessage());
            return result;
        }
    }

    @Override
    public BankEntity getBankById(String id) {
        return bankReadService.getBankById(id);
    }


    @Override
    public BankEntity getBankByFamilyId(String id,String memberId,String businessCode) {
        return bankReadService.getBankByFamilyIdEdit(id,memberId,businessCode);
    }



    @Override
    public ExcelInfo exportBank(BankParam param, UserAccountVo accountVo){
        ExcelInfo excelInfo = null;
        QueryParamUtil.setBaseParamValue(param,accountVo);

        if(Constant.BusinessCode.DIBAO.equals(param.getBusinessType())){
            List<BankExcelMinDTO> list  = bankReadService.exportBankMin(param);

            excelInfo = exportExcelService.exportOrgOpLogs(BankExcelMinDTO.class,list,"最低生活保障银行账号登记信息.xls",
                    "最低生活保障银行账号登记列表","最低生活保障银行账号登记列表",false,null);
        } else if (Constant.BusinessCode.TEKUN.equals(param.getBusinessType())){
            List<BankExcelDTO> list  = bankReadService.exportBank(param);

            excelInfo = exportExcelService.exportOrgOpLogs(BankExcelDTO.class,list,"特困人员救助供养银行账号登记信息.xls",
                    "特困人员救助供养银行账号登记列表","特困人员救助供养银行账号登记列表",false,null);
        } else {
            List<BankExcelDTO> list  = bankReadService.exportBank(param);

            excelInfo = exportExcelService.exportOrgOpLogs(BankExcelDTO.class,list,"临时救助银行账号登记信息.xls",
                    "临时救助银行账号登记列表","临时救助银行账号登记列表",false,null);
        }


        return excelInfo;
    }

    @Override
    public Page getTempBankPage(UserAccountVo curUserAccount, BankParam param, PageParam pageParam) {

        QueryParamUtil.setBaseParamValue(param, curUserAccount);

        param.setRescueyears(CommonUtil.invalidArgs(param.getRescueyears()) ? DateUtil.getMonthString() : param.getRescueyears());

        return bankReadService.getTempBankPage(param, pageParam);
    }
}
